package cn.com.pansky.action.common;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.alibaba.fastjson.JSONObject;

import net.vsame.url2sql.action.CommonAction;
import net.vsame.url2sql.exception.Url2SqlErrorException;
import net.vsame.url2sql.helper.SqlHelper;
import net.vsame.url2sql.sql.Model;
import cn.com.pansky.action.imgContrast.ImgContrast;
import cn.com.pansky.action.logs.Log;
import cn.com.pansky.service.CommonService;
import cn.com.pansky.util.HttpUtil;
import cn.com.pansky.util.LssConstant;
import cn.com.pansky.util.MD5Util;
public class AccountAction extends CommonAction{

	private Log log = new Log();
	CommonService cs = new CommonService();
	/**
	 * 修改密码
	 */
	public void changePass() {
		String oldPass = MD5Util.string2MD5(context.getParam("AA002"));
		String newPass = MD5Util.string2MD5(context.getParam("AA002_1"));
		String sql = urlConfig.getVar("getOldPassord");
		Model m = SqlHelper.queryOne(sql);
		if(m.getString("AA002").equals(oldPass)) {
			SqlHelper.execute(urlConfig.getVar("updatePass"), newPass, m.getString("AA001"));
			datas.put("isPass", true);
			datas.put("info", "修改成功，请重新登陆");
		}else{
			datas.put("isPass", false);
			datas.put("info", "原密码输入错误");
		}
		context.getDatas().put("result", datas);
	}
	
	/**
	 * 实名认证
	 * @throws Exception
	 */
	public void certification() throws Exception {

		String AA032 = user.getString("AA032");
		String findCA001 = urlConfig.getVar("findCA001");
		Model m = SqlHelper.queryOne(findCA001, AA032);
		String CA001 = m.getString("CA001");
		
		//日志记录start
		String AF001 = log.start(CA001, "SM");
		
		String findInfo = urlConfig.getVar("findInfo");
		Model mm = SqlHelper.queryOne(findInfo, CA001);
		String imgPath = getParam("img"); // 身份证图片
		// 获取刷脸图片
		String image_best = getParam("image_best");
		String image_env = getParam("image_env");
		String delta = getParam("delta");
		
		File file = new File(imgPath);// 身份证上传后的临时文件
		File file2 = new File(image_best);// 刷脸上传后的临时文件
		JSONObject json = new JSONObject();
		if (!file.exists() || !file2.exists()) {
			json.put("isPass", false); // 认证失败
			json.put("info", "身份证或刷脸照片不可为空"); // 认证失败
		} else {
			//比对身份证和刷脸照片
			JSONObject result = ImgContrast.imgCompare(imgPath, image_best, image_env, delta);
			if(0 != result.getIntValue("code")){
				json.put("isPass", false);
				json.put("info", "请确认身份证与刷脸是同一人！");
				context.getDatas().put("result", json);
			}else{
				
				double num = result.getDoubleValue("confidence");
				// 判断照片相似度
				if (num  > LssConstant.CONFIDENCE) {
					
					// 判断库中是否有这个人的特征信息：
					String findFeatures = urlConfig.getVar("findFeatures");
					Model mmm = SqlHelper.queryOne(findFeatures, CA001);
					String id = "";
					if (mmm != null) {
						id = mmm.getString("CA011");
					}
					cs.isnertRC06(image_best, CA001, num, id);
					file2.delete();
				} else {
					json.put("isPass", false);
					json.put("info", "请确认身份证与刷脸是同一人！");
					context.getDatas().put("result", json);
					file.delete();
					file2.delete();
					//日志记录end
					boolean result1 = log.end(AF001, json.getString("isPass"), json.getString("info"));
					System.out.println("实名认证记录"+result1);
					return;
				}
			}
			
			json = cs.idendetify(file.getPath());

			if (mm.getString("CA003").equals(json.getString("CA003"))
					&& mm.getString("CA006").equals(json.getString("CA006"))) {
				// 认证成功
				// 如果认证成功，则将民族，性别，出生年月，图片更新至用户信息中
				String sql = urlConfig.getVar("mergeUserByCardId");
				SqlHelper.execute(sql, json.getString("CA009"),
						cs.getValueByName("AAC005", json.getString("CA051")),
						cs.getAac004(json.getString("CA050")),
						json.getString("CA052"), CA001);

				// 根据服务对象id查询是否有身份证文件
				String s1 = urlConfig.getVar("queryRC05Byca001");
				Model m2 = SqlHelper.queryOne(s1, CA001);
				String id = "";
				if (m2 != null) {
					id = m2.getString("CA020");
				}
				// 说明该用户不存在身份证文件，新增该条信息
				cs.isnertRC05(CA001, imgPath, id);
				file.delete(); // 删除身份证图片临时文件
				String updRC10ByAA032 = urlConfig.getVar("updRC10ByAA032");
				String aa032 = user.getString("AA032");
				SqlHelper.execute(updRC10ByAA032, aa032);
				json.put("isPass", true);
				json.put("info", "恭喜您实名认证成功");
				json.put("AA111", 1);
			} else {
				json.put("isPass", false); // 认证失败
				json.put("info", "身份证姓名与注册时填写信息不一致！"); // 认证失败
			}
		}
		System.out.println(json);
		//日志记录end
		boolean result = log.end(AF001, json.getString("isPass"), json.getString("info"));
		System.out.println("日志：实名认证"+result);

		context.getDatas().put("result", json);
	}
	
	/**
	 * 我的账户-手机号修改
	 */
	public void changeTel(){
		//日志记录start
		String AF001 = log.start(" ", "UP");
		
		String sql = "select * from RC10 where AA032 = ? and aa003 = ?";
		String AA032_1 = getParam("AA032_1");
		Model mm = SqlHelper.queryOne(sql, AA032_1, user.getString("AA003"));
		System.out.println(user.getString("AA003")+"===="+user.getString("AA032"));
		JSONObject result = new JSONObject();
		if (null != mm) {
			result.put("isPass", false);
			result.put("info", "您输入的手机号已存在，请更换其他手机号");
		} else {
			//刷脸---根据身份证号查询服务对象id
			String findCA001 = urlConfig.getVar("findCA001");
			Model m = SqlHelper.queryOne(findCA001, user.getString("AA032"),user.getString("AA003"));
			String CA001 = m.getString("CA001");
			//获取刷脸图片
			String image_best = getParam("image_best");
			String image_env = getParam("image_env");
			String delta = getParam("delta");
			// 指定身份证照片保存路径：
			String filename = "";
			Properties p = new Properties();
			try {
				p.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
			} catch (IOException e) {
				e.printStackTrace();
				System.out.print("---------------------");
				throw new Url2SqlErrorException(-1, "服务异常，请联系管理员");
			}
			// 指定身份证照片保存路径：
			filename = p.getProperty("imgPath") + CA001 + ".jpg";
			cs.getIdcardPic(CA001, filename);

			//调用照片比对方法，比对刷脸与身份证照片
//			double num = ImgContrast.imgContrast(filename, imgPath);
			JSONObject json = ImgContrast.imgCompare(filename, image_best, image_env, delta);
			if(0 != json.getIntValue("code")){
				datas.put("isPass", false);
				datas.put("info", "请确认身份证与刷脸是同一人！");
			}else{
				double num = json.getDoubleValue("confidence");
				if (num>LssConstant.CONFIDENCE) {
					String updateRC10 = urlConfig.getVar("updateRC10");
					String updateRC12 = urlConfig.getVar("updateRC12");
					
					SqlHelper.execute(updateRC10, AA032_1,AA032_1, user.getString("AA032"),user.getString("AA003"));
					
					String findOldPhone = urlConfig.getVar("findOldPhone");
					List<Model> list = SqlHelper.query(findOldPhone, user.getString("AA032"));
					if (list.size()>0) {
						SqlHelper.execute(updateRC12, AA032_1, user.getString("AA032"));	
					}
					context.getServletSession().removeAttribute("user");
					result.put("isPass", true);
					result.put("info", "修改成功，请重新登陆");
				}else{
					result.put("isPass", false);
					result.put("info", "面部特征校验失败，请确保是用户本人操作！");
				}
			}
			//将身份证临时照片删除
			File file = new File(filename);
			file.delete();
			//将刷脸图片删除
			File file2 = new File(image_best);
			file2.delete();
			File file3 = new File(image_env);
			file3.delete();
		}
		//日志记录end
		boolean results = log.end(AF001, result.get("isPass"), result.get("info"));
		System.out.println("日志：修改手机号"+results);
		context.put("result", result);
	}
	
	public void test() throws KeyManagementException, NoSuchAlgorithmException, IOException{
		Map<String, String> files = new HashMap<String, String>();
		Map<String, String> params = new HashMap<String, String>();
		files.put("image", "/weblogic/Oracle/Middleware/Oracle_Home/user_projects/domains/base_domain/temp/1.JPG");
		// 1.调用远程接口
		HttpUtil.enableAllHost();
		String result = HttpUtil.post(LssConstant.FACE_URL_IDCARD, params, files);
		context.put("data", result);
	}
	
	
	public static void main(String[] args) {
		System.out.println(MD5Util.string2MD5("qaz123"));
	}
}
